# 网易卡搭自动扒源器
# zengyl制作，遵循CC-BY-SA-4.0协议开源


import json,zipfile,sys,os


# 自动判断并安装requests库
try:
    import requests
except:
    print("\n您没有安装requests库，正在为您自动安装！");
    os.system(sys.executable + " -m pip install requests");
    print("安装完成！");
    import requests


headers = {#请求头
    'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36'
}
version = "0.3";#程序版本


#更新程序
update = requests.get("https://gitee.com/Zeng_YL/kadaBaYuan/raw/data/version.json",headers=headers).json();
if(update["version"] > version):#有新版本
    print("\n发现一个于" + update["time"] + "发布的新版本" + update["version"] + "（当前版本" + version + "），更新内容：");
    for v in update["updates"]:#输出更新内容
        if(v <= version):
            break;
        print(v + "：" + update["updates"][v]);
    print("是否更新？（y/n）");
    i = input();
    print("更新中……");
    if(i == 'y' or i == 'Y'):#开始更新
        f = open(os.path.abspath(__file__),'wb');
        f.write(requests.get("https://gitee.com/Zeng_YL/kadaBaYuan/raw/master/main.py",headers=headers).content);
        f.close;
    print("更新完成，重启程序生效！");
    exit();


urlP = input("\n请输入卡搭作品网址：");
#判断网址是否有效
try:
    page = requests.get(urlP, headers=headers).text;

    s = page.find("steam", page.find("projectUrl",page.find("projectInfo")));
    e = page.find("\"", s);
    
    JSON = requests.get("http://" + page[s:e], headers=headers).json();
except:
    print("网址错误！");
    exit();

if("targets" not in JSON):#不是Sc3文件
    print("文件类型错误！");
    exit();

media = [];

for target in JSON["targets"]:
    for costume in target["costumes"]:
        media.append(costume);
    for i, sound in enumerate(target["sounds"]):
        media.append(sound);
        target["sounds"][i]["assetId"] = target["sounds"][i]["assetId"].replace("-", "");
        target["sounds"][i]["md5ext"] = target["sounds"][i]["md5ext"].replace("-", "");

f = open("project.json","w",encoding="utf-8");
f.write(json.dumps(JSON));
f.close();

zf = zipfile.ZipFile(os.path.dirname(os.path.abspath(__file__)) + "\\Project.sb3","w");
zf.write("project.json");

os.remove("project.json");

for m in media:
    url = "";
    if(m["kadaId"] == -1):
        url = "http://steam.nosdn.127.net/" + m["md5ext"];
    else:
        url = "http:" + m["assetStore"] + m["md5ext"];
    f = open(m["md5ext"].replace("-", ""), "wb");
    f.write(requests.get(url, headers=headers).content);
    f.close();
    zf.write(m["md5ext"].replace("-", ""));
    os.remove(m["md5ext"].replace("-", ""));

zf.close();

print("完成！");